package com.bot.devbot.service.wechat;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import com.bot.devbot.properties.HookUrlConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 企业微信机器人接口封装
 * <a href="https://developer.work.weixin.qq.com/document/path/91770">企业微信机器人</a>
 * > 需要\n\n <@%s>
 * <a href="https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot?lang=zh-CN">企业微信机器人文档</a>
 *
 * @author xialiguo
 * @version 1.0
 * @date 2025/1/21 15:41
 * @since 1.0
 */
@Slf4j
@Service
public class WeChatService {

    private String weChatWebhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ce920d47-4916-4ac8-8297-f73ccc88ba33";
    @Autowired
    private HookUrlConfig hookUrlConfig;

    // gitlab提交作者信息与企微ID的映射
    private static Map<String, String> AUTHOR_WECHAT_USER_MAPPING = new HashMap<>();

    public static Map<String, String> getAuthorWechatUserMapping() {
        if (CollUtil.isEmpty(AUTHOR_WECHAT_USER_MAPPING)) {
            synchronized (WeChatService.class) {
                if (AUTHOR_WECHAT_USER_MAPPING == null) {
                    AUTHOR_WECHAT_USER_MAPPING = new HashMap<>();
                }
                AUTHOR_WECHAT_USER_MAPPING.put("毛福江", "maofujiang");
                AUTHOR_WECHAT_USER_MAPPING.put("maofujiang", "maofujiang");
                AUTHOR_WECHAT_USER_MAPPING.put("zhuwenxu", "zhuwenxu");
                AUTHOR_WECHAT_USER_MAPPING.put("朱文旭", "zhuwenxu");
                AUTHOR_WECHAT_USER_MAPPING.put("黄宇辰", "huangyuchen");
                AUTHOR_WECHAT_USER_MAPPING.put("huangyuchen", "huangyuchen");
                AUTHOR_WECHAT_USER_MAPPING.put("刘鸿", "liuhong");
                AUTHOR_WECHAT_USER_MAPPING.put("liuhong", "liuhong");
                AUTHOR_WECHAT_USER_MAPPING.put("罗云鹏", "luoyunpeng");
                AUTHOR_WECHAT_USER_MAPPING.put("luoyunpeng", "luoyunpeng");
                AUTHOR_WECHAT_USER_MAPPING.put("李佳文", "lijiawen");
                AUTHOR_WECHAT_USER_MAPPING.put("lijiawen", "lijiawen");
                AUTHOR_WECHAT_USER_MAPPING.put("Li jia wen", "lijiawen");
                AUTHOR_WECHAT_USER_MAPPING.put("蔡世金", "caishijin");
                AUTHOR_WECHAT_USER_MAPPING.put("caishijin", "caishijin");
                AUTHOR_WECHAT_USER_MAPPING.put("夏利国", "xialiguo");
                AUTHOR_WECHAT_USER_MAPPING.put("xialiguo", "xialiguo");
                AUTHOR_WECHAT_USER_MAPPING.put("范奇伟", "fanqiwei");
                AUTHOR_WECHAT_USER_MAPPING.put("fanqiwei", "fanqiwei");
                AUTHOR_WECHAT_USER_MAPPING.put("fanic", "fanqiwei");
                AUTHOR_WECHAT_USER_MAPPING.put("蒋义琪", "jiangyiqi");
                AUTHOR_WECHAT_USER_MAPPING.put("jiangyiqi", "jiangyiqi");
                AUTHOR_WECHAT_USER_MAPPING.put("Plt-蒋义琪", "jiangyiqi");
                AUTHOR_WECHAT_USER_MAPPING.put("张永平", "zhangyongping");
                AUTHOR_WECHAT_USER_MAPPING.put("zhangyongping", "zhangyongping");
            }
        }
        return AUTHOR_WECHAT_USER_MAPPING;
    }


    public void sendMessageTxt(String message) {
        JSONObject body = new JSONObject();
        body.put("msgtype", "text");
        JSONObject text = new JSONObject();
        text.put("content", message);
        body.put("text", text);

        HttpRequest.post(weChatWebhook)
                .body(body.toString())
                .execute();
    }

    public void sendMessageMd(String projectName, String message) {

        JSONObject body = new JSONObject();
        body.put("msgtype", "markdown");
        JSONObject text = new JSONObject();
        text.put("content", message);
        body.put("markdown", text);

        HttpRequest.post(weChatWebhook)
                .body(body.toString())
                .execute();
    }

    public void sendMessageMdV2FromCnf(String projectName, String branchName, String author,String message) {
        List<HookUrlConfig.PrjHookUrl> targetConfigs = findMatchingConfigs(projectName);
        if (CollUtil.isEmpty(targetConfigs)) {
            log.warn("未找到项目:{}对应的企业微信配置;提醒消息:{}", projectName, message);
            return;
        }
        Map<String, String> authorWechatUserMapping = getAuthorWechatUserMapping();
        String authorWechatUser = authorWechatUserMapping.get(author);
        for (HookUrlConfig.PrjHookUrl targetConfig : targetConfigs) {
            String webhookUrl = targetConfig.getWechatUrl();
            List<String> userIds = targetConfig.getUserIds();
            List<String> testUserIds = targetConfig.getTestUserIds();
            // 艾特处理
            if (CollUtil.isNotEmpty(userIds)) {
                StringBuilder atContent = new StringBuilder();
                for (String userId : userIds) {
                    // 艾特人员排除作者
                    if (userId.equals(authorWechatUser)) {
                        log.info("跳过@{}，因为是作者", userId);
                        continue;
                    }
                    atContent.append("<@").append(userId).append(">");
                }
                message = message + "\n\n" + atContent;
            }
            // 测试人员艾特处理
            if (CollUtil.isNotEmpty(testUserIds) && "test".equals(branchName)) {
                StringBuilder atContent = new StringBuilder();
                for (String userId : testUserIds) {
                    atContent.append("<@").append(userId).append(">");
                }
                message = message + atContent;
            }

            JSONObject body = new JSONObject();
            body.put("msgtype", "markdown");
            JSONObject markdown = new JSONObject();
            markdown.put("content", message);
            body.put("markdown", markdown);
            HttpRequest.post(webhookUrl)
                    .body(body.toString())
                    .execute();
        }
    }


    private List<HookUrlConfig.PrjHookUrl> findMatchingConfigs(String projectName) {
        if (hookUrlConfig == null || hookUrlConfig.getPrjHookUrlMap() == null) {
            return Collections.emptyList();
        }

        List<HookUrlConfig.PrjHookUrl> matchingConfigs = new ArrayList<>();
        for (HookUrlConfig.PrjHookUrl config : hookUrlConfig.getPrjHookUrlMap()) {
            List<String> prjNames = config.getPrjName();
            if (CollUtil.isNotEmpty(prjNames) && prjNames.contains(projectName)) {
                matchingConfigs.add(config);
            }
        }
        return matchingConfigs;
    }
}
